﻿using anydata.Handlers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace anydata.Models
{
    [ModelBinder(BinderType = typeof(TokenModelBinder))]
    public class TokenModel
    {
        public ulong UserId { get; set; }
        public ulong BelongId { get; set; }

        public string DbName => $"DB{BelongId}".ToBase32();

        public string ObjectKey(string name)
        {
            return $"{BelongId}-Object-{name}";
        }
        public string CollectionKey(string name)
        {
            return $"{BelongId}-Collection-{name}";
        }
    }

    public class TokenModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var accessToken = bindingContext.HttpContext.Request.Headers.Authorization.ToString();
            var token = TokenHanlder.Read(accessToken);
            if (bindingContext.HttpContext.Request.Query.TryGetValue("belongId", out var param) 
                && ulong.TryParse(param.ToString(), out ulong belongId) && belongId > 0)
            {
                token.BelongId = belongId;
            }
            bindingContext.Result = ModelBindingResult.Success(token);
            return Task.CompletedTask;
        }
    }
}
